# Definition for singly-linked list.
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        l1_r = self.reverse_list(l1)
        l2_r = self.reverse_list(l2)

        dummy = ListNode()
        cur = dummy
        j = 0
        l1_rc = l1_r
        l2_rc = l2_r
        while l1_rc or l2_rc or j > 0:
            add = 0
            if l1_rc:
                add += l1_rc.val
                l1_rc = l1_rc.next
            if l2_rc:
                add += l2_rc.val
                l2_rc = l2_rc.next
            add += j
            cur.next = ListNode(add % 10, None)
            cur = cur.next
            j = 1 if add > 9 else 0
        return self.reverse_list(dummy.next)

    def reverse_list(self, head: Optional[ListNode]):
        if not head:
            return head
        pre = None
        cur = head
        while cur:
            nxt = cur.next
            cur.next = pre
            pre = cur
            cur = nxt
        return pre
